#pragma once
#include <vector>
using namespace std;

namespace pqu
{
    template<class T>
    class Less
    {
    public:
        bool operator()(T x, T y)
        {
            return x < y;
        }
    };

    template<class T>
    class Greater
    {
    public:
        bool operator()(T x, T y)
        {
            return x > y;
        }
    };

    template<class T, class Container = vector<T>, class Compare = Less<T> >
    class priority_queue
    {
    public:
        priority_queue(){}
        template<class InputIterator>
        priority_queue(InputIterator first, InputIterator last)
            : _con(first, last)
        {
            // 建堆
            for (int i = (_con.size() - 2) / 2; i >= 0; --i)
            {
                //从最后一个叶子节点的父节点开始向下调整
                adjust_down(i);
            }
        }

        // 向上调整
        void adjust_up(int child)
        {
            // 通过仿函数，就可以控制实现的是小堆还是大堆
            Compare com;
            int parent = (child - 1) / 2;
            while (child > 0)
            {
                if (com(_con[parent], _con[child]))
                {
                    swap(_con[child], _con[parent]);
                    child = parent;
                    parent = (child - 1) / 2;
                } else break;
            }
        }

        // 向下调整
        void adjust_down(int parent)
        {
            Compare com;
            // 假设左孩子优先级高
            int child = parent * 2 + 1;
            while (child < _con.size())
            {
                // 若存在右孩子节点，且右孩子优先级比左孩子高
                if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
                {
                    ++child;
                }
                if (com(_con[parent], _con[child]))
                {
                    swap(_con[child], _con[parent]);
                    parent = child;
                    child = parent * 2 + 1;
                } else break;
            }
        }

        void push(const T &val)
        {
            _con.push_back(val);
            adjust_up(_con.size() - 1);
        }

        void pop()
        {
            swap(_con[0], _con[_con.size() - 1]);
            _con.pop_back();
            adjust_down(0);
        }

        const T &top() const
        {
            return _con[0];
        }

        bool empty()
        {
            return _con.empty();
        }

        size_t size()
        {
            return _con.size();
        }

    private:
        Container _con;
    };
}
